<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2017/8/27
 * Time: 20:49
 */

namespace app\api\controller;

use think\Controller;
use think\exception\HttpResponseException;
use think\Request;
use think\Response;
use Firebase\JWT\JWT;

class BaseController extends Controller
{
    public function _initialize()
    {
        if (strpos($this->beforeActionList['Authorization']['except'], strtolower($this->request->action()))) {
            $this->updateToken(false);
        }
    }

    protected $beforeActionList = [
        'Authorization' => ['except' => 'login,send_mobile_vcode,get_upload_token,post_callback,distinct_list']
    ];

    protected function customizedResult($success = true, $data, $errorCode = '', $errorMsg = '', array $header = [])
    {
        $result = [
            'success' => $success,
            'data' => $data,
            'error_code' => $errorCode,
            'error_msg' => $errorMsg
        ];
        $type = "json";
        $response = Response::create($result, $type)->header($header);
        throw new HttpResponseException($response);
    }

    protected function Authorization()
    {
        $this->updateToken(true);
    }

    private function noAccess()
    {
        $this->customizedResult(false, null, "10001", "请登陆");
    }

    /**更新token
     * @param $requireToken 是否必须token
     */
    private function updateToken($requireToken)
    {
        $token = Request::instance()->header('token');
        if (isset($token)) {
            $secretKey = 'bomeiyi';
            // 定义载荷
            $currentTime = time();
            $expTime = $currentTime + 30 * 24 * 3600;//30天


            try {
                $decoded = JWT::decode($token, $secretKey, array('HS256'));
                if ($decoded->exp < $currentTime) {
                    if ($requireToken) {
                        $this->noAccess();
                    }
                } else {
                    $payload = array(
                        'iat' => $currentTime, // 有效期
                        'exp' => $expTime,
                        'data' => array(
                            'user_id' => $decoded->data->user_id,
                        )
                    );
                    Request::instance()->bind('worker_user', $decoded->data);
                    $privateToken = JWT::encode($payload, $secretKey);
                    header('token:' . $privateToken);
                }
            } catch (\Exception    $e) {
                if ($requireToken) {
                    $this->noAccess();
                }
            }
        } else {
            if ($requireToken) {
                $this->noAccess();
            }
        }
    }


    protected function http($url, $param = array())
    {
        $ch = curl_init();

        if (substr($url, 0, 5) == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true); // 从证书中检查SSL加密算法是否存在
        }

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($param));

        $response = curl_exec($ch);

        if ($error = curl_error($ch)) {
            return false;
        }

        curl_close($ch);

        return $response;
    }

    protected function gpsConvert($lat, $lng)
    {
        // baidu_map_ak
        $url = "http://api.map.baidu.com/geocoder/v2/";
        $param = array(
            'ak' => config("baidu_map_ak"),
            'location' => implode(',', array(
                $lat,
                $lng
            )),
            'output' => 'json'
        );

        return $this->http($url, $param);
    }
}